import router from './router';
import store from './store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Dialog } from 'vant';
import getPageTitle from '@/utils/getPageTitle';
import { getToken } from '@/utils/auth';
import { getConstellation, bumen } from '@/api/gain';

NProgress.configure({ showSpinner: false });

// const whiteList = ['/login', '/home', '/Activities', '/ActiveDetails']
const whiteList = ['/login'];

router.beforeEach(async(to, from, next) => {
    NProgress.start();
    const { meta } = to;

    document.title = getPageTitle(meta.title);

    // 控制页头和底部导航
    store.dispatch('app/toggleHeader', meta);
    store.dispatch('app/toggleNavbar', meta);

    // 验证登录
    const hasToken = getToken();

    if (hasToken) {
        if (to.path === '/login') {
            // if is logged in, redirect to the home page
            next({ path: '/' });
        } else {
            await store.dispatch('user/getInfo');
            const hasGetUserInfo = store.getters.userInfo;
            // 获取星座列表
            const res = await getConstellation();
            store.dispatch('utils/saveXinzuo', res.data);
            // 获取部门列表
            const bumenRes = await bumen();
            store.dispatch('utils/saveBumen', bumenRes.data);
            if (hasGetUserInfo) {
                next();
            } else {
                try {
                    // get user info
                    const res = await store.dispatch('user/getInfo');
                    if (res === null) {
                        Dialog.alert({
                            title: '请重新登录',
                            message: `你已被退出登录`
                        });
                        await store.dispatch('user/logout');
                        next({ path: '/login' });
                        return;
                    }
                    next();
                } catch (error) {
                    // remove token and go to login page to re-login
                    await store.dispatch('user/resetToken');
                    next(`/login?redirect=${to.path}`);
                }
            }
        }
    } else {
        /* 用户未登录*/
        if (whiteList.indexOf(to.path) !== -1) {
            // 用户当前在白名单页面中
            next();
        } else {
            // 用户如果不在白名单页面中则跳转至登录页
            next(`/login?redirect=${to.name}`);
        }
    }
});

router.afterEach(() => {
    // 路由导航结束后关闭加载进度条
    NProgress.done();
});
